import datetime
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import desc, or_
from app.models import Feedback, User, AdminLog
from app.core.extensions import db
from . import admin_blueprint
from app.services.decorators import admin_required


@admin_blueprint.route('/feedbacks', methods=['GET', 'OPTIONS'])
@jwt_required(optional=True)
def get_feedbacks():
    """获取反馈列表
    
    查询参数:
    - page: 页码，默认1
    - per_page: 每页数量，默认20
    - search: 搜索关键词
    - status: 状态筛选（0-未处理, 1-已处理）
    - start_date: 开始日期（格式：YYYY-MM-DD）
    - end_date: 结束日期（格式：YYYY-MM-DD）
    - user_id: 按用户ID筛选
    """
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    search = request.args.get('search', '')
    status = request.args.get('status', '')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')
    user_id = request.args.get('user_id', '')
    
    # 构建查询
    query = Feedback.query
    
    # 根据状态筛选
    if status:
        try:
            status = int(status)
            query = query.filter(Feedback.status == status)
        except (ValueError, TypeError):
            return jsonify({'code': 1, 'message': '状态必须是数字'}), 400
    
    # 根据用户ID筛选
    if user_id:
        try:
            user_id = int(user_id)
            query = query.filter(Feedback.user_id == user_id)
        except (ValueError, TypeError):
            return jsonify({'code': 1, 'message': '用户ID必须是数字'}), 400
    
    # 根据日期范围筛选
    if start_date:
        try:
            start_datetime = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            query = query.filter(Feedback.create_time >= start_datetime)
        except ValueError:
            return jsonify({'code': 1, 'message': '开始日期格式不正确'}), 400
    
    if end_date:
        try:
            end_datetime = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            # 将结束日期设置为当天的23:59:59
            end_datetime = end_datetime.replace(hour=23, minute=59, second=59)
            query = query.filter(Feedback.create_time <= end_datetime)
        except ValueError:
            return jsonify({'code': 1, 'message': '结束日期格式不正确'}), 400
    
    # 关键词搜索
    if search:
        query = query.filter(
            or_(
                Feedback.content.like(f'%{search}%'),
                Feedback.contact.like(f'%{search}%')
            )
        )
    
    # 执行分页查询
    pagination = query.order_by(desc(Feedback.create_time)).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    feedbacks = pagination.items
    
    # 构建响应数据
    result = {
        'code': 0,
        'message': '获取成功',
        'data': {
            'total': pagination.total,
            'pages': pagination.pages,
            'page': page,
            'per_page': per_page,
            'items': [feedback_to_dict(feedback) for feedback in feedbacks]
        }
    }
    
    return jsonify(result)


@admin_blueprint.route('/feedbacks/<int:feedback_id>', methods=['GET','OPTIONS'])
@jwt_required(optional=True)
def get_feedback(feedback_id):
    """获取反馈详情"""
    feedback = Feedback.query.get(feedback_id)
    if not feedback:
        return jsonify({'code': 1, 'message': '反馈不存在'}), 404
    
    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': feedback_to_dict(feedback)
    })


@admin_blueprint.route('/feedbacks/reply/<int:feedback_id>', methods=['POST','OPTIONS'])
@jwt_required()
@admin_required
def reply_feedback(feedback_id):
    """回复反馈"""
    feedback = Feedback.query.get_or_404(feedback_id)
    # 获取回复内容
    data = request.get_json()
    if not data or 'reply' not in data:
        return jsonify({'code': 1, 'message': '回复内容不能为空'}), 400
    
    reply = data.get('reply', '').strip()
    if not reply:
        return jsonify({'code': 1, 'message': '回复内容不能为空'}), 400
    
    # 更新反馈
    feedback.reply = reply
    feedback.reply_time = datetime.datetime.now()
    feedback.status = 1  # 已处理
    
    # 添加操作日志
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action='回复反馈',
        ip=request.remote_addr,
        details=f'回复反馈 ID: {feedback.id}'
    )
    db.session.add(log)
    
    db.session.commit()
    
    return jsonify({
        'code': 0,
        'message': '回复成功',
        'data': feedback_to_dict(feedback)
    })


@admin_blueprint.route('/feedbacks/status/<int:feedback_id>', methods=['POST','OPTIONS'])
@jwt_required()
@admin_required
def update_feedback_status(feedback_id):
    """更新反馈状态"""
    feedback = Feedback.query.get_or_404(feedback_id)
    
    # 获取状态
    data = request.get_json()
    if not data or 'status' not in data:
        return jsonify({'code': 1, 'message': '状态不能为空'}), 400
    
    try:
        status = int(data.get('status'))
        if status not in [0, 1]:
            return jsonify({'code': 1, 'message': '状态值无效'}), 400
    except (ValueError, TypeError):
        return jsonify({'code': 1, 'message': '状态必须是数字'}), 400
    
    # 更新状态
    feedback.status = status
    
    # 如果标记为已处理但没有回复，自动添加默认回复
    if status == 1 and not feedback.reply:
        feedback.reply = "管理员已处理"
        feedback.reply_time = datetime.datetime.now()
    
    # 添加操作日志
    status_text = '已处理' if status == 1 else '未处理'
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action='更新反馈状态',
        ip=request.remote_addr,
        details=f'将反馈 ID: {feedback.id} 状态设置为 {status_text}'
    )
    db.session.add(log)
    
    db.session.commit()
    
    return jsonify({
        'code': 0,
        'message': '状态更新成功',
        'data': feedback_to_dict(feedback)
    })


@admin_blueprint.route('/feedbacks/delete/<int:feedback_id>', methods=['POST','OPTIONS'])
@admin_required
def delete_feedback(feedback_id):
    """删除反馈"""
    feedback = Feedback.query.get_or_404(feedback_id)
    
    # 添加操作日志
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action='删除反馈',
        ip=request.remote_addr,
        details=f'删除反馈 ID: {feedback.id}'
    )
    db.session.add(log)
    
    # 删除反馈
    db.session.delete(feedback)
    db.session.commit()
    
    return jsonify({
        'code': 0,
        'message': '删除成功'
    })


def feedback_to_dict(feedback):
    """将反馈对象转换为字典"""
    # 获取用户信息
    user = User.query.get(feedback.user_id) if feedback.user_id else None
    
    return {
        'id': feedback.id,
        'user_id': feedback.user_id,
        'content': feedback.content,
        'contact': feedback.contact,
        'status': feedback.status,
        'create_time': feedback.create_time.strftime('%Y-%m-%d %H:%M:%S') if feedback.create_time else None,
        'reply': feedback.reply,
        'reply_time': feedback.reply_time.strftime('%Y-%m-%d %H:%M:%S') if feedback.reply_time else None,
        'user': {
            'nick_name': user.nick_name if user else None,
            'mobile': user.mobile if user else None
        } if user else None
    }